package com.apicloud.faceVisaInterface;

import com.android.snetjob.JobRequest;
import com.android.snetjob.RequestBuilder;
import com.face.bsdk.FVSdk;

import com.facevisa.view.extract.ExtractActivity;
import com.facevisa.view.living.LivingActivity;
import com.facevisa.view.ocr.OcrScanActivity;
import com.facevisa.view.ocr.OcrSfzBean;
import com.facevisa.view.util.FileUtil;
import com.facevisa.view.util.JPGUtil;
import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;


import java.util.HashMap;
import java.util.Map;
import android.app.AlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.Toast;


public class UZFaceVisa extends UZModule {

	public static final String FV_CACHE = "/facevisa/cache";
	public static String APPINFO = "5bb7b13a2ff7779da18a78e1c6672dc2c94aa836e9be71b904fb0bc6268aa2504ad9d443b2ce1d65ab1fdcc3256861593c2bd268b218786a1390f72c8653724f";

	protected static final int REQ_CODE = 100;
	public static final String LCONFIG = "living_config";
	public static final String SAFE_MODE = "safe_mode"; 
	public static final String CHECK_MODE = "check_mode"; 
	public static final String TIME_OUT = "5";  //默认5检测5秒超时
	public static final String DELAY = "1"; // 活体单个动作延时时间(秒)
	public static final String SAFE ="";// 安全模式
	public static final String CAMERA = "camera"; 
	public static final String SHOW_DEF_PAGE = "show_def"; 
	public static final String SHOW_LOCATION = "show_location"; 
	public static final String RESULT_JUMP = "result_jump"; 
	public static final int LIVING = 0x7f07001a;
	
	private UZModuleContext mJsCallback;
	


	private static Map<String, String> lParam = new HashMap<String, String>();

	public UZFaceVisa(UZWebView webView) {
		super(webView);
	}

	public void jsmethod_pictureCompare(final UZModuleContext moduleContext) {
		
	}

	public void jsmethod_living(final UZModuleContext moduleContext) {
		
		startLiving(moduleContext);
	}
	
	public String getLParam(String key) {
		return lParam.get(key);
	}
	
	
	private void startLiving(UZModuleContext moduleContext) {
		//处理参数
		//APPINFO
		String appInfo = moduleContext.optString("appInfo");
		if( null != appInfo && "" != appInfo) APPINFO = appInfo;
		
		//是否显示展示窗口
		String showStart = moduleContext.optString("showStart");
		if(null == showStart) showStart = "true";			
		
		//单个动作检测超时时间
		String timeout = String.valueOf(moduleContext.optInt("timeout"));
		if(null == timeout && "" == timeout) timeout = "5";		
		//单个动作检测延迟时间
		String delay = String.valueOf(moduleContext.optString("delay"));
		if(null == delay && "" == delay) delay = "1";		
		
		//检测模式
		String safeMode = moduleContext.optString("safeMode");
		//安全模式 默认为low
		if ("high".equals(safeMode))
			safeMode = FVSdk.FVSafeMode.FVSafeHighMode.name();
		else if ("medium".equals(safeMode))
			safeMode = FVSdk.FVSafeMode.FVSafeMediumMode.name();
		else if ("low".equals(safeMode))
			safeMode = FVSdk.FVSafeMode.FVSafeLowMode.name();
		else
			safeMode = FVSdk.FVSafeMode.FVSafeLowMode.name();
		
				
		//是否显示人脸位置
		String showLocation = moduleContext.optString("showLocation");
		if(null ==showLocation ) showLocation = "true";
		
		//检测模式
		String checkMode = moduleContext.optString("checkMode");
		if ("fast".equals(checkMode))
			checkMode = FVSdk.FVLivingMode.FVLivingFastMode.name();
		else if ("base".equals(checkMode))
			checkMode = FVSdk.FVLivingMode.FVLivingBaseMode.name();
		else if ("standard".equals(checkMode))
			checkMode = FVSdk.FVLivingMode.FVLivingStandardMode.name();
		else if ("advanced".equals(checkMode))
			checkMode = FVSdk.FVLivingMode.FVLivingAdvancedMode.name();
		else if("self".equals(checkMode))
			checkMode = FVSdk.FVLivingMode.FVLivingCustomedMode.name();
		else
			checkMode = FVSdk.FVLivingMode.FVLivingBaseMode.name();			
		
		
		//默认false, 打开摄像头(true:后置 false:前置)
		String backCamera = moduleContext.optString("backCamera");	
		if(null == backCamera) backCamera = "false";
		

		String sdp = Environment.getExternalStorageDirectory().toString();
		String ndp = String.format("%s%s", sdp, "/facevisa/living");
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(LivingActivity.REQ_APP_INFO, APPINFO); 
		map.put(LivingActivity.REQ_SHOW_START, showStart); 
		map.put(LivingActivity.REQ_TIME_OUT, timeout); 
		map.put(LivingActivity.REQ_DELAY, delay); 
		map.put(LivingActivity.REQ_SAFE_MODE, safeMode); 
		map.put(LivingActivity.REQ_SAVE_PATH, ndp); 
		map.put(LivingActivity.REQ_BACK_CAMERA, backCamera); 
		map.put(LivingActivity.REQ_SHOW_LOCATION, showLocation); 
		
		
		//如果是自定文模式
		String reqCustom = moduleContext.optString("reqCustom");
		if("FVLivingCustomedMode".equals(checkMode) && null!=reqCustom)  {
			map.put(LivingActivity.REQ_CHECK_MODE, checkMode);			
			//这里需要判断自定文的动作 以后再写
			map.put(LivingActivity.REQ_CUSTOM,  reqCustom);     			
		}else{
			map.put(LivingActivity.REQ_CHECK_MODE, checkMode); 
		}
		
		mJsCallback = moduleContext;
		Intent intent = LivingActivity.createIntent(getContext(), map, null);
		startActivityForResult(intent, REQ_CODE);
	}
	

	
	 @Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		
		 
		// 活体结果回馈
		if (requestCode == 100 && resultCode == LivingActivity.RESULT_CODE) {
			if (data != null) {
				int code = data.getIntExtra(LivingActivity.RES_CODE, -1);
				try {	
					JSONObject ret = new JSONObject();
					if(code == 0 ){
						
						ret.put("status", true);
						ret.put("imgPath",data.getStringExtra(LivingActivity.RES_PATH));
						
						//mJsCallback = null;				
					}else{										
						ret.put("status", false);	
					}
					
					//mJsCallback.success(ret, false);
					
					JSONObject err = new JSONObject();
					err.put("code", code);	
					
					JSONObject msg = new JSONObject();				
					if(code == 0)	err.put("msg", "活体成功");
					else if(code == -1)	err.put("msg", "SDK初始化失败");
					else if(code == -2)	err.put("msg", "参数解析失败");
					else if(code == -3)	err.put("msg", "活体失败");
					else if(code == -4)	err.put("msg", "活体异常");
					else if(code == -5)	err.put("msg", "受权失败");
					mJsCallback.error(ret, err,false);
					mJsCallback = null;

										
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
		 // 人脸提取
		else if (requestCode == REQ_CODE && resultCode == ExtractActivity.RESULT_CODE) {
            if (data != null) {
                int code = data.getIntExtra(ExtractActivity.RES_CODE, -1);
                try {	
	                JSONObject ret = new JSONObject();
	                if (code == 0) {
	                    // 提取成功
	                    String facePath = data.getStringExtra(ExtractActivity.RES_PATH);
	                    Bitmap bitmap = BitmapFactory.decodeFile(facePath);
	                    
	                    ret.put("status",true);
						ret.put("imgPath",data.getStringExtra(ExtractActivity.RES_PATH));
	                } else {
	                    // 提取失败
	                    //String msg = data.getStringExtra(OcrScanActivity.RES_MESS);
	                   // Toast.makeText(this, String.format("code:%d msg:%s", code, msg), Toast.LENGTH_SHORT).show();
	                    ret.put("status", false);	
	                }
	                
	                JSONObject err = new JSONObject();
					err.put("code", code);	
					
					JSONObject msg = new JSONObject();				
					if(code == 0)	err.put("msg", "活体成功");
					else if(code == -1)	err.put("msg", "SDK初始化失败");
					else if(code == -2)	err.put("msg", "参数解析失败");
					else if(code == -3)	err.put("msg", "活体失败");
					else if(code == -4)	err.put("msg", "活体异常");
					else if(code == -5)	err.put("msg", "受权失败");
					mJsCallback.error(ret, err,false);
					mJsCallback = null;
					
            	} catch (JSONException e) {
					e.printStackTrace();
				}
            }
        }
		
		else{
			try {	
                JSONObject ret = new JSONObject();
               
                ret.put("status",false);					
                JSONObject err = new JSONObject();				
				JSONObject msg = new JSONObject();				
				err.put("code", 100);	
				err.put("msg", "其它错误");
				mJsCallback.error(ret, err,false);
				mJsCallback = null;
				
        	} catch (JSONException e) {
				e.printStackTrace();
			}
			
		}
	}
	 
	 public static void ShowMsg(String msg,Context context) {
	        AlertDialog.Builder dlg = new AlertDialog.Builder(context);
	        dlg.setTitle("提示");
	        dlg.setMessage(msg);
	        dlg.setPositiveButton("确定",null);
	        dlg.show();
	  } 
	
	 public void jsmethod_startExtract(final UZModuleContext moduleContext) {
			
		 startExtract(moduleContext);
		}
	
	 private void startExtract(UZModuleContext moduleContext) {
		 	//最大人脸数
			String maxFaceCount =  String.valueOf(moduleContext.optInt("maxCount"));
			if(null == maxFaceCount) maxFaceCount = "1";			
			
			//单个动作检测超时时间
			String stime = String.valueOf(moduleContext.optInt("stime"));
			if(null == stime && "" == stime) stime = "2";		
			
			//默认false, 打开摄像头(true:后置 false:前置)
			String backCamera = moduleContext.optString("backCamera");	
			if(null == backCamera) backCamera = "false";
			
			//检测模式
			String outPutMode =  moduleContext.optString("outPutMode");
						
			if ("maxscore".equals(outPutMode))
				outPutMode = "FVOnlyMaxScore";
			else if ("bigface".equals(outPutMode))
				outPutMode = "FVOnlyBigFace";
			else if ("centerface".equals(outPutMode))
				outPutMode = "FVOnlyCenterFace";
			else
				outPutMode = "FVOnlyBigFace";			
			
			
	        // 1.设置图片存放目录
	        String sdp = Environment.getExternalStorageDirectory().toString();
	        String ndp = String.format("%s%s", sdp, "/facevisa/extract");
	        // 2.清空目录
	        FileUtil.delFiles(ndp);
	        // 3.配置活体检查
	        HashMap<String, String> map = new HashMap<String, String>();
	       // map.put(LivingActivity.REQ_APP_INFO, APPINFO); 
	        map.put(ExtractActivity.REQ_SAVE_PATH,  ndp);                // 结果存放目录
	        map.put(ExtractActivity.REQ_MAX_FACE_COUNT,  maxFaceCount);  // 最大人脸数
	        map.put(ExtractActivity.REQ_OUTPUT_MODE,  outPutMode); // 仅输出最高分人脸
	        map.put(ExtractActivity.REQ_OUTPUT_SPACE, stime);             // 结果输出间隔2秒
	        map.put(ExtractActivity.REQ_BACK_CAMERA, backCamera);          // 使用前置摄像头
	        mJsCallback = moduleContext;
	        // 4.启动提取界面
	        Intent intent = ExtractActivity.createIntent(getContext(), map);
	        startActivityForResult(intent, REQ_CODE);
	    }   

}
